home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / pymodules / python2.6 / configobj.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-02  |  68KB  |  2,129 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. from __future__ import generators
  5. import sys
  6. INTP_VER = sys.version_info[:2]
  7. if INTP_VER < (2, 2):
  8.     raise RuntimeError('Python v.2.2 or later needed')
  9. INTP_VER < (2, 2)
  10. import os
  11. import re
  12. compiler = None
  13.  
  14. try:
  15.     import compiler
  16. except ImportError:
  17.     pass
  18.  
  19. from types import StringTypes
  20. from warnings import warn
  21.  
  22. try:
  23.     from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE
  24. except ImportError:
  25.     BOM_UTF8 = '\xef\xbb\xbf'
  26.     BOM_UTF16_LE = '\xff\xfe'
  27.     BOM_UTF16_BE = '\xfe\xff'
  28.     if sys.byteorder == 'little':
  29.         BOM_UTF16 = BOM_UTF16_LE
  30.     else:
  31.         BOM_UTF16 = BOM_UTF16_BE
  32. except:
  33.     sys.byteorder == 'little'
  34.  
  35. BOMS = {
  36.     BOM_UTF8: ('utf_8', None),
  37.     BOM_UTF16_BE: ('utf16_be', 'utf_16'),
  38.     BOM_UTF16_LE: ('utf16_le', 'utf_16'),
  39.     BOM_UTF16: ('utf_16', 'utf_16') }
  40. BOM_LIST = {
  41.     'utf_16': 'utf_16',
  42.     'u16': 'utf_16',
  43.     'utf16': 'utf_16',
  44.     'utf-16': 'utf_16',
  45.     'utf16_be': 'utf16_be',
  46.     'utf_16_be': 'utf16_be',
  47.     'utf-16be': 'utf16_be',
  48.     'utf16_le': 'utf16_le',
  49.     'utf_16_le': 'utf16_le',
  50.     'utf-16le': 'utf16_le',
  51.     'utf_8': 'utf_8',
  52.     'u8': 'utf_8',
  53.     'utf': 'utf_8',
  54.     'utf8': 'utf_8',
  55.     'utf-8': 'utf_8' }
  56. BOM_SET = {
  57.     'utf_8': BOM_UTF8,
  58.     'utf_16': BOM_UTF16,
  59.     'utf16_be': BOM_UTF16_BE,
  60.     'utf16_le': BOM_UTF16_LE,
  61.     None: BOM_UTF8 }
  62.  
  63. def match_utf8(encoding):
  64.     return BOM_LIST.get(encoding.lower()) == 'utf_8'
  65.  
  66. squot = "'%s'"
  67. dquot = '"%s"'
  68. noquot = '%s'
  69. wspace_plus = ' \r\t\n\x0b\t\'"'
  70. tsquot = '"""%s"""'
  71. tdquot = "'''%s'''"
  72.  
  73. try:
  74.     enumerate
  75. except NameError:
  76.     
  77.     def enumerate(obj):
  78.         '''enumerate for Python 2.2.'''
  79.         i = -1
  80.         for item in obj:
  81.             i += 1
  82.             yield (i, item)
  83.         
  84.  
  85.  
  86.  
  87. try:
  88.     (True, False)
  89. except NameError:
  90.     (True, False) = (1, 0)
  91.  
  92. __version__ = '4.5.3'
  93. __revision__ = '$Id: configobj.py 156 2006-01-31 14:57:08Z fuzzyman $'
  94. __docformat__ = 'restructuredtext en'
  95. __all__ = ('__version__', 'DEFAULT_INDENT_TYPE', 'DEFAULT_INTERPOLATION', 'ConfigObjError', 'NestingError', 'ParseError', 'DuplicateError', 'ConfigspecError', 'ConfigObj', 'SimpleVal', 'InterpolationError', 'InterpolationLoopError', 'MissingInterpolationOption', 'RepeatSectionError', 'ReloadError', 'UnreprError', 'UnknownType', '__docformat__', 'flatten_errors')
  96. DEFAULT_INTERPOLATION = 'configparser'
  97. DEFAULT_INDENT_TYPE = '    '
  98. MAX_INTERPOL_DEPTH = 10
  99. OPTION_DEFAULTS = {
  100.     'interpolation': True,
  101.     'raise_errors': False,
  102.     'list_values': True,
  103.     'create_empty': False,
  104.     'file_error': False,
  105.     'configspec': None,
  106.     'stringify': True,
  107.     'indent_type': None,
  108.     'encoding': None,
  109.     'default_encoding': None,
  110.     'unrepr': False,
  111.     'write_empty_values': False }
  112.  
  113. def getObj(s):
  114.     s = 'a=' + s
  115.     if compiler is None:
  116.         raise ImportError('compiler module not available')
  117.     compiler is None
  118.     p = compiler.parse(s)
  119.     return p.getChildren()[1].getChildren()[0].getChildren()[1]
  120.  
  121.  
  122. class UnknownType(Exception):
  123.     pass
  124.  
  125.  
  126. class Builder(object):
  127.     
  128.     def build(self, o):
  129.         m = getattr(self, 'build_' + o.__class__.__name__, None)
  130.         if m is None:
  131.             raise UnknownType(o.__class__.__name__)
  132.         m is None
  133.         return m(o)
  134.  
  135.     
  136.     def build_List(self, o):
  137.         return map(self.build, o.getChildren())
  138.  
  139.     
  140.     def build_Const(self, o):
  141.         return o.value
  142.  
  143.     
  144.     def build_Dict(self, o):
  145.         d = { }
  146.         i = iter(map(self.build, o.getChildren()))
  147.         for el in i:
  148.             d[el] = i.next()
  149.         
  150.         return d
  151.  
  152.     
  153.     def build_Tuple(self, o):
  154.         return tuple(self.build_List(o))
  155.  
  156.     
  157.     def build_Name(self, o):
  158.         if o.name == 'None':
  159.             return None
  160.         if o.name == 'True':
  161.             return True
  162.         if o.name == 'False':
  163.             return False
  164.         raise UnknownType('Undefined Name')
  165.  
  166.     
  167.     def build_Add(self, o):
  168.         (real, imag) = map(self.build_Const, o.getChildren())
  169.         
  170.         try:
  171.             real = float(real)
  172.         except TypeError:
  173.             raise UnknownType('Add')
  174.  
  175.         if not isinstance(imag, complex) or imag.real != 0:
  176.             raise UnknownType('Add')
  177.         imag.real != 0
  178.         return real + imag
  179.  
  180.     
  181.     def build_Getattr(self, o):
  182.         parent = self.build(o.expr)
  183.         return getattr(parent, o.attrname)
  184.  
  185.     
  186.     def build_UnarySub(self, o):
  187.         return -self.build_Const(o.getChildren()[0])
  188.  
  189.     
  190.     def build_UnaryAdd(self, o):
  191.         return self.build_Const(o.getChildren()[0])
  192.  
  193.  
  194. _builder = Builder()
  195.  
  196. def unrepr(s):
  197.     if not s:
  198.         return s
  199.     return _builder.build(getObj(s))
  200.  
  201.  
  202. class ConfigObjError(SyntaxError):
  203.     '''
  204.     This is the base class for all errors that ConfigObj raises.
  205.     It is a subclass of SyntaxError.
  206.     '''
  207.     
  208.     def __init__(self, message = '', line_number = None, line = ''):
  209.         self.line = line
  210.         self.line_number = line_number
  211.         self.message = message
  212.         SyntaxError.__init__(self, message)
  213.  
  214.  
  215.  
  216. class NestingError(ConfigObjError):
  217.     """
  218.     This error indicates a level of nesting that doesn't match.
  219.     """
  220.     pass
  221.  
  222.  
  223. class ParseError(ConfigObjError):
  224.     '''
  225.     This error indicates that a line is badly written.
  226.     It is neither a valid ``key = value`` line,
  227.     nor a valid section marker line.
  228.     '''
  229.     pass
  230.  
  231.  
  232. class ReloadError(IOError):
  233.     """
  234.     A 'reload' operation failed.
  235.     This exception is a subclass of ``IOError``.
  236.     """
  237.     
  238.     def __init__(self):
  239.         IOError.__init__(self, 'reload failed, filename is not set.')
  240.  
  241.  
  242.  
  243. class DuplicateError(ConfigObjError):
  244.     '''
  245.     The keyword or section specified already exists.
  246.     '''
  247.     pass
  248.  
  249.  
  250. class ConfigspecError(ConfigObjError):
  251.     '''
  252.     An error occured whilst parsing a configspec.
  253.     '''
  254.     pass
  255.  
  256.  
  257. class InterpolationError(ConfigObjError):
  258.     '''Base class for the two interpolation errors.'''
  259.     pass
  260.  
  261.  
  262. class InterpolationLoopError(InterpolationError):
  263.     '''Maximum interpolation depth exceeded in string interpolation.'''
  264.     
  265.     def __init__(self, option):
  266.         InterpolationError.__init__(self, 'interpolation loop detected in value "%s".' % option)
  267.  
  268.  
  269.  
  270. class RepeatSectionError(ConfigObjError):
  271.     '''
  272.     This error indicates additional sections in a section with a
  273.     ``__many__`` (repeated) section.
  274.     '''
  275.     pass
  276.  
  277.  
  278. class MissingInterpolationOption(InterpolationError):
  279.     '''A value specified for interpolation was missing.'''
  280.     
  281.     def __init__(self, option):
  282.         InterpolationError.__init__(self, 'missing option "%s" in interpolation.' % option)
  283.  
  284.  
  285.  
  286. class UnreprError(ConfigObjError):
  287.     '''An error parsing in unrepr mode.'''
  288.     pass
  289.  
  290.  
  291. class InterpolationEngine(object):
  292.     '''
  293.     A helper class to help perform string interpolation.
  294.  
  295.     This class is an abstract base class; its descendants perform
  296.     the actual work.
  297.     '''
  298.     _KEYCRE = re.compile('%\\(([^)]*)\\)s')
  299.     
  300.     def __init__(self, section):
  301.         self.section = section
  302.  
  303.     
  304.     def interpolate(self, key, value):
  305.         
  306.         def recursive_interpolate(key, value, section, backtrail):
  307.             """The function that does the actual work.
  308.  
  309.             ``value``: the string we're trying to interpolate.
  310.             ``section``: the section in which that string was found
  311.             ``backtrail``: a dict to keep track of where we've been,
  312.             to detect and prevent infinite recursion loops
  313.  
  314.             This is similar to a depth-first-search algorithm.
  315.             """
  316.             if backtrail.has_key((key, section.name)):
  317.                 raise InterpolationLoopError(key)
  318.             backtrail.has_key((key, section.name))
  319.             backtrail[(key, section.name)] = 1
  320.             match = self._KEYCRE.search(value)
  321.             while match:
  322.                 (k, v, s) = self._parse_match(match)
  323.                 if k is None:
  324.                     replacement = v
  325.                 else:
  326.                     replacement = recursive_interpolate(k, v, s, backtrail)
  327.                 (start, end) = match.span()
  328.                 value = ''.join((value[:start], replacement, value[end:]))
  329.                 new_search_start = start + len(replacement)
  330.                 match = self._KEYCRE.search(value, new_search_start)
  331.             del backtrail[(key, section.name)]
  332.             return value
  333.  
  334.         value = recursive_interpolate(key, value, self.section, { })
  335.         return value
  336.  
  337.     
  338.     def _fetch(self, key):
  339.         '''Helper function to fetch values from owning section.
  340.  
  341.         Returns a 2-tuple: the value, and the section where it was found.
  342.         '''
  343.         save_interp = self.section.main.interpolation
  344.         self.section.main.interpolation = False
  345.         current_section = self.section
  346.         while True:
  347.             val = current_section.get(key)
  348.             if val is not None:
  349.                 break
  350.             
  351.             val = current_section.get('DEFAULT', { }).get(key)
  352.             if val is not None:
  353.                 break
  354.             
  355.             if current_section.parent is current_section:
  356.                 break
  357.             
  358.             current_section = current_section.parent
  359.         self.section.main.interpolation = save_interp
  360.         if val is None:
  361.             raise MissingInterpolationOption(key)
  362.         val is None
  363.         return (val, current_section)
  364.  
  365.     
  366.     def _parse_match(self, match):
  367.         '''Implementation-dependent helper function.
  368.  
  369.         Will be passed a match object corresponding to the interpolation
  370.         key we just found (e.g., "%(foo)s" or "$foo"). Should look up that
  371.         key in the appropriate config file section (using the ``_fetch()``
  372.         helper function) and return a 3-tuple: (key, value, section)
  373.  
  374.         ``key`` is the name of the key we\'re looking for
  375.         ``value`` is the value found for that key
  376.         ``section`` is a reference to the section where it was found
  377.  
  378.         ``key`` and ``section`` should be None if no further
  379.         interpolation should be performed on the resulting value
  380.         (e.g., if we interpolated "$$" and returned "$").
  381.         '''
  382.         raise NotImplementedError()
  383.  
  384.  
  385.  
  386. class ConfigParserInterpolation(InterpolationEngine):
  387.     '''Behaves like ConfigParser.'''
  388.     _KEYCRE = re.compile('%\\(([^)]*)\\)s')
  389.     
  390.     def _parse_match(self, match):
  391.         key = match.group(1)
  392.         (value, section) = self._fetch(key)
  393.         return (key, value, section)
  394.  
  395.  
  396.  
  397. class TemplateInterpolation(InterpolationEngine):
  398.     '''Behaves like string.Template.'''
  399.     _delimiter = '$'
  400.     _KEYCRE = re.compile('\n        \\$(?:\n          (?P<escaped>\\$)              |   # Two $ signs\n          (?P<named>[_a-z][_a-z0-9]*)  |   # $name format\n          {(?P<braced>[^}]*)}              # ${name} format\n        )\n        ', re.IGNORECASE | re.VERBOSE)
  401.     
  402.     def _parse_match(self, match):
  403.         if not match.group('named'):
  404.             pass
  405.         key = match.group('braced')
  406.         if key is not None:
  407.             (value, section) = self._fetch(key)
  408.             return (key, value, section)
  409.         if match.group('escaped') is not None:
  410.             return (None, self._delimiter, None)
  411.         return (None, match.group(), None)
  412.  
  413.  
  414. interpolation_engines = {
  415.     'configparser': ConfigParserInterpolation,
  416.     'template': TemplateInterpolation }
  417.  
  418. class Section(dict):
  419.     """
  420.     A dictionary-like object that represents a section in a config file.
  421.     
  422.     It does string interpolation if the 'interpolation' attribute
  423.     of the 'main' object is set to True.
  424.     
  425.     Interpolation is tried first from this object, then from the 'DEFAULT'
  426.     section of this object, next from the parent and its 'DEFAULT' section,
  427.     and so on until the main object is reached.
  428.     
  429.     A Section will behave like an ordered dictionary - following the
  430.     order of the ``scalars`` and ``sections`` attributes.
  431.     You can use this to change the order of members.
  432.     
  433.     Iteration follows the order: scalars, then sections.
  434.     """
  435.     
  436.     def __init__(self, parent, depth, main, indict = None, name = None):
  437.         '''
  438.         * parent is the section above
  439.         * depth is the depth level of this section
  440.         * main is the main ConfigObj
  441.         * indict is a dictionary to initialise the section with
  442.         '''
  443.         if indict is None:
  444.             indict = { }
  445.         
  446.         dict.__init__(self)
  447.         self.parent = parent
  448.         self.main = main
  449.         self.depth = depth
  450.         self.name = name
  451.         self._initialise()
  452.         for entry, value in indict.iteritems():
  453.             self[entry] = value
  454.         
  455.  
  456.     
  457.     def _initialise(self):
  458.         self.scalars = []
  459.         self.sections = []
  460.         self.comments = { }
  461.         self.inline_comments = { }
  462.         self.configspec = { }
  463.         self._order = []
  464.         self._configspec_comments = { }
  465.         self._configspec_inline_comments = { }
  466.         self._cs_section_comments = { }
  467.         self._cs_section_inline_comments = { }
  468.         self.defaults = []
  469.         self.default_values = { }
  470.  
  471.     
  472.     def _interpolate(self, key, value):
  473.         
  474.         try:
  475.             engine = self._interpolation_engine
  476.         except AttributeError:
  477.             name = self.main.interpolation
  478.             if name == True:
  479.                 name = DEFAULT_INTERPOLATION
  480.             
  481.             name = name.lower()
  482.             class_ = interpolation_engines.get(name, None)
  483.             if class_ is None:
  484.                 self.main.interpolation = False
  485.                 return value
  486.         except:
  487.             engine = self._interpolation_engine = class_(self)
  488.  
  489.         return engine.interpolate(key, value)
  490.  
  491.     
  492.     def __getitem__(self, key):
  493.         '''Fetch the item and do string interpolation.'''
  494.         val = dict.__getitem__(self, key)
  495.         if self.main.interpolation and isinstance(val, StringTypes):
  496.             return self._interpolate(key, val)
  497.         return val
  498.  
  499.     
  500.     def __setitem__(self, key, value, unrepr = False):
  501.         """
  502.         Correctly set a value.
  503.         
  504.         Making dictionary values Section instances.
  505.         (We have to special case 'Section' instances - which are also dicts)
  506.         
  507.         Keys must be strings.
  508.         Values need only be strings (or lists of strings) if
  509.         ``main.stringify`` is set.
  510.         
  511.         `unrepr`` must be set when setting a value to a dictionary, without
  512.         creating a new sub-section.
  513.         """
  514.         if not isinstance(key, StringTypes):
  515.             raise ValueError('The key "%s" is not a string.' % key)
  516.         isinstance(key, StringTypes)
  517.         if not self.comments.has_key(key):
  518.             self.comments[key] = []
  519.             self.inline_comments[key] = ''
  520.         
  521.         if key in self.defaults:
  522.             self.defaults.remove(key)
  523.         
  524.         if isinstance(value, Section):
  525.             if not self.has_key(key):
  526.                 self.sections.append(key)
  527.             
  528.             dict.__setitem__(self, key, value)
  529.         elif isinstance(value, dict) and not unrepr:
  530.             if not self.has_key(key):
  531.                 self.sections.append(key)
  532.             
  533.             new_depth = self.depth + 1
  534.             dict.__setitem__(self, key, Section(self, new_depth, self.main, indict = value, name = key))
  535.         elif not self.has_key(key):
  536.             self.scalars.append(key)
  537.         
  538.         if not self.main.stringify:
  539.             if isinstance(value, StringTypes):
  540.                 pass
  541.             elif isinstance(value, (list, tuple)):
  542.                 for entry in value:
  543.                     if not isinstance(entry, StringTypes):
  544.                         raise TypeError('Value is not a string "%s".' % entry)
  545.                     isinstance(entry, StringTypes)
  546.                 
  547.             else:
  548.                 raise TypeError('Value is not a string "%s".' % value)
  549.         isinstance(value, StringTypes)
  550.         dict.__setitem__(self, key, value)
  551.  
  552.     
  553.     def __delitem__(self, key):
  554.         '''Remove items from the sequence when deleting.'''
  555.         dict.__delitem__(self, key)
  556.         if key in self.scalars:
  557.             self.scalars.remove(key)
  558.         else:
  559.             self.sections.remove(key)
  560.         del self.comments[key]
  561.         del self.inline_comments[key]
  562.  
  563.     
  564.     def get(self, key, default = None):
  565.         """A version of ``get`` that doesn't bypass string interpolation."""
  566.         
  567.         try:
  568.             return self[key]
  569.         except KeyError:
  570.             return default
  571.  
  572.  
  573.     
  574.     def update(self, indict):
  575.         '''
  576.         A version of update that uses our ``__setitem__``.
  577.         '''
  578.         for entry in indict:
  579.             self[entry] = indict[entry]
  580.         
  581.  
  582.     
  583.     def pop(self, key, *args):
  584.         """
  585.         'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  586.         If key is not found, d is returned if given, otherwise KeyError is raised'
  587.         """
  588.         val = dict.pop(self, key, *args)
  589.         if key in self.scalars:
  590.             del self.comments[key]
  591.             del self.inline_comments[key]
  592.             self.scalars.remove(key)
  593.         elif key in self.sections:
  594.             del self.comments[key]
  595.             del self.inline_comments[key]
  596.             self.sections.remove(key)
  597.         
  598.         if self.main.interpolation and isinstance(val, StringTypes):
  599.             return self._interpolate(key, val)
  600.         return val
  601.  
  602.     
  603.     def popitem(self):
  604.         '''Pops the first (key,val)'''
  605.         sequence = self.scalars + self.sections
  606.         if not sequence:
  607.             raise KeyError(": 'popitem(): dictionary is empty'")
  608.         sequence
  609.         key = sequence[0]
  610.         val = self[key]
  611.         del self[key]
  612.         return (key, val)
  613.  
  614.     
  615.     def clear(self):
  616.         '''
  617.         A version of clear that also affects scalars/sections
  618.         Also clears comments and configspec.
  619.         
  620.         Leaves other attributes alone :
  621.             depth/main/parent are not affected
  622.         '''
  623.         dict.clear(self)
  624.         self.scalars = []
  625.         self.sections = []
  626.         self.comments = { }
  627.         self.inline_comments = { }
  628.         self.configspec = { }
  629.  
  630.     
  631.     def setdefault(self, key, default = None):
  632.         '''A version of setdefault that sets sequence if appropriate.'''
  633.         
  634.         try:
  635.             return self[key]
  636.         except KeyError:
  637.             self[key] = default
  638.             return self[key]
  639.  
  640.  
  641.     
  642.     def items(self):
  643.         """D.items() -> list of D's (key, value) pairs, as 2-tuples"""
  644.         return zip(self.scalars + self.sections, self.values())
  645.  
  646.     
  647.     def keys(self):
  648.         """D.keys() -> list of D's keys"""
  649.         return self.scalars + self.sections
  650.  
  651.     
  652.     def values(self):
  653.         """D.values() -> list of D's values"""
  654.         return [ self[key] for key in self.scalars + self.sections ]
  655.  
  656.     
  657.     def iteritems(self):
  658.         '''D.iteritems() -> an iterator over the (key, value) items of D'''
  659.         return iter(self.items())
  660.  
  661.     
  662.     def iterkeys(self):
  663.         '''D.iterkeys() -> an iterator over the keys of D'''
  664.         return iter(self.scalars + self.sections)
  665.  
  666.     __iter__ = iterkeys
  667.     
  668.     def itervalues(self):
  669.         '''D.itervalues() -> an iterator over the values of D'''
  670.         return iter(self.values())
  671.  
  672.     
  673.     def __repr__(self):
  674.         '''x.__repr__() <==> repr(x)'''
  675.         return [] % []([ '%s: %s' % (repr(key), repr(self[key])) for key in self.scalars + self.sections ])
  676.  
  677.     __str__ = __repr__
  678.     __str__.__doc__ = 'x.__str__() <==> str(x)'
  679.     
  680.     def dict(self):
  681.         '''
  682.         Return a deepcopy of self as a dictionary.
  683.         
  684.         All members that are ``Section`` instances are recursively turned to
  685.         ordinary dictionaries - by calling their ``dict`` method.
  686.         
  687.         >>> n = a.dict()
  688.         >>> n == a
  689.         1
  690.         >>> n is a
  691.         0
  692.         '''
  693.         newdict = { }
  694.         for entry in self:
  695.             this_entry = self[entry]
  696.             if isinstance(this_entry, Section):
  697.                 this_entry = this_entry.dict()
  698.             elif isinstance(this_entry, list):
  699.                 this_entry = list(this_entry)
  700.             elif isinstance(this_entry, tuple):
  701.                 this_entry = tuple(this_entry)
  702.             
  703.             newdict[entry] = this_entry
  704.         
  705.         return newdict
  706.  
  707.     
  708.     def merge(self, indict):
  709.         """
  710.         A recursive update - useful for merging config files.
  711.         
  712.         >>> a = '''[section1]
  713.         ...     option1 = True
  714.         ...     [[subsection]]
  715.         ...     more_options = False
  716.         ...     # end of file'''.splitlines()
  717.         >>> b = '''# File is user.ini
  718.         ...     [section1]
  719.         ...     option1 = False
  720.         ...     # end of file'''.splitlines()
  721.         >>> c1 = ConfigObj(b)
  722.         >>> c2 = ConfigObj(a)
  723.         >>> c2.merge(c1)
  724.         >>> c2
  725.         {'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}
  726.         """
  727.         for key, val in indict.items():
  728.             if key in self and isinstance(self[key], dict) and isinstance(val, dict):
  729.                 self[key].merge(val)
  730.                 continue
  731.             self[key] = val
  732.         
  733.  
  734.     
  735.     def rename(self, oldkey, newkey):
  736.         '''
  737.         Change a keyname to another, without changing position in sequence.
  738.         
  739.         Implemented so that transformations can be made on keys,
  740.         as well as on values. (used by encode and decode)
  741.         
  742.         Also renames comments.
  743.         '''
  744.         if oldkey in self.scalars:
  745.             the_list = self.scalars
  746.         elif oldkey in self.sections:
  747.             the_list = self.sections
  748.         else:
  749.             raise KeyError('Key "%s" not found.' % oldkey)
  750.         pos = (oldkey in self.scalars).index(oldkey)
  751.         val = self[oldkey]
  752.         dict.__delitem__(self, oldkey)
  753.         dict.__setitem__(self, newkey, val)
  754.         the_list.remove(oldkey)
  755.         the_list.insert(pos, newkey)
  756.         comm = self.comments[oldkey]
  757.         inline_comment = self.inline_comments[oldkey]
  758.         del self.comments[oldkey]
  759.         del self.inline_comments[oldkey]
  760.         self.comments[newkey] = comm
  761.         self.inline_comments[newkey] = inline_comment
  762.  
  763.     
  764.     def walk(self, function, raise_errors = True, call_on_sections = False, **keywargs):
  765.         """
  766.         Walk every member and call a function on the keyword and value.
  767.         
  768.         Return a dictionary of the return values
  769.         
  770.         If the function raises an exception, raise the errror
  771.         unless ``raise_errors=False``, in which case set the return value to
  772.         ``False``.
  773.         
  774.         Any unrecognised keyword arguments you pass to walk, will be pased on
  775.         to the function you pass in.
  776.         
  777.         Note: if ``call_on_sections`` is ``True`` then - on encountering a
  778.         subsection, *first* the function is called for the *whole* subsection,
  779.         and then recurses into it's members. This means your function must be
  780.         able to handle strings, dictionaries and lists. This allows you
  781.         to change the key of subsections as well as for ordinary members. The
  782.         return value when called on the whole subsection has to be discarded.
  783.         
  784.         See  the encode and decode methods for examples, including functions.
  785.         
  786.         .. admonition:: Caution
  787.         
  788.             You can use ``walk`` to transform the names of members of a section
  789.             but you mustn't add or delete members.
  790.         
  791.         >>> config = '''[XXXXsection]
  792.         ... XXXXkey = XXXXvalue'''.splitlines()
  793.         >>> cfg = ConfigObj(config)
  794.         >>> cfg
  795.         {'XXXXsection': {'XXXXkey': 'XXXXvalue'}}
  796.         >>> def transform(section, key):
  797.         ...     val = section[key]
  798.         ...     newkey = key.replace('XXXX', 'CLIENT1')
  799.         ...     section.rename(key, newkey)
  800.         ...     if isinstance(val, (tuple, list, dict)):
  801.         ...         pass
  802.         ...     else:
  803.         ...         val = val.replace('XXXX', 'CLIENT1')
  804.         ...         section[newkey] = val
  805.         >>> cfg.walk(transform, call_on_sections=True)
  806.         {'CLIENT1section': {'CLIENT1key': None}}
  807.         >>> cfg
  808.         {'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}}
  809.         """
  810.         out = { }
  811.         for i in range(len(self.scalars)):
  812.             entry = self.scalars[i]
  813.             
  814.             try:
  815.                 val = function(self, entry, **keywargs)
  816.                 entry = self.scalars[i]
  817.                 out[entry] = val
  818.             continue
  819.             except Exception:
  820.                 if raise_errors:
  821.                     raise 
  822.                 raise_errors
  823.                 entry = self.scalars[i]
  824.                 out[entry] = False
  825.                 continue
  826.             
  827.  
  828.         
  829.         for i in range(len(self.sections)):
  830.             entry = self.sections[i]
  831.             if call_on_sections:
  832.                 
  833.                 try:
  834.                     function(self, entry, **keywargs)
  835.                 except Exception:
  836.                     None<EXCEPTION MATCH>Exception
  837.                     None<EXCEPTION MATCH>Exception
  838.                     if raise_errors:
  839.                         raise 
  840.                     raise_errors
  841.                     entry = self.sections[i]
  842.                     out[entry] = False
  843.                 except:
  844.                     None<EXCEPTION MATCH>Exception
  845.  
  846.                 entry = self.sections[i]
  847.             
  848.             out[entry] = self[entry].walk(function, raise_errors = raise_errors, call_on_sections = call_on_sections, **keywargs)
  849.         
  850.         return out
  851.  
  852.     
  853.     def decode(self, encoding):
  854.         """
  855.         Decode all strings and values to unicode, using the specified encoding.
  856.         
  857.         Works with subsections and list values.
  858.         
  859.         Uses the ``walk`` method.
  860.         
  861.         Testing ``encode`` and ``decode``.
  862.         >>> m = ConfigObj(a)
  863.         >>> m.decode('ascii')
  864.         >>> def testuni(val):
  865.         ...     for entry in val:
  866.         ...         if not isinstance(entry, unicode):
  867.         ...             print >> sys.stderr, type(entry)
  868.         ...             raise AssertionError, 'decode failed.'
  869.         ...         if isinstance(val[entry], dict):
  870.         ...             testuni(val[entry])
  871.         ...         elif not isinstance(val[entry], unicode):
  872.         ...             raise AssertionError, 'decode failed.'
  873.         >>> testuni(m)
  874.         >>> m.encode('ascii')
  875.         >>> a == m
  876.         1
  877.         """
  878.         warn('use of ``decode`` is deprecated.', DeprecationWarning)
  879.         
  880.         def decode(section, key, encoding = encoding, warn = True):
  881.             ''' '''
  882.             val = section[key]
  883.             if isinstance(val, (list, tuple)):
  884.                 newval = []
  885.                 for entry in val:
  886.                     newval.append(entry.decode(encoding))
  887.                 
  888.             elif isinstance(val, dict):
  889.                 newval = val
  890.             else:
  891.                 newval = val.decode(encoding)
  892.             newkey = key.decode(encoding)
  893.             section.rename(key, newkey)
  894.             section[newkey] = newval
  895.  
  896.         self.walk(decode, call_on_sections = True)
  897.  
  898.     
  899.     def encode(self, encoding):
  900.         '''
  901.         Encode all strings and values from unicode,
  902.         using the specified encoding.
  903.         
  904.         Works with subsections and list values.
  905.         Uses the ``walk`` method.
  906.         '''
  907.         warn('use of ``encode`` is deprecated.', DeprecationWarning)
  908.         
  909.         def encode(section, key, encoding = encoding):
  910.             ''' '''
  911.             val = section[key]
  912.             if isinstance(val, (list, tuple)):
  913.                 newval = []
  914.                 for entry in val:
  915.                     newval.append(entry.encode(encoding))
  916.                 
  917.             elif isinstance(val, dict):
  918.                 newval = val
  919.             else:
  920.                 newval = val.encode(encoding)
  921.             newkey = key.encode(encoding)
  922.             section.rename(key, newkey)
  923.             section[newkey] = newval
  924.  
  925.         self.walk(encode, call_on_sections = True)
  926.  
  927.     
  928.     def istrue(self, key):
  929.         '''A deprecated version of ``as_bool``.'''
  930.         warn('use of ``istrue`` is deprecated. Use ``as_bool`` method instead.', DeprecationWarning)
  931.         return self.as_bool(key)
  932.  
  933.     
  934.     def as_bool(self, key):
  935.         '''
  936.         Accepts a key as input. The corresponding value must be a string or
  937.         the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
  938.         retain compatibility with Python 2.2.
  939.         
  940.         If the string is one of  ``True``, ``On``, ``Yes``, or ``1`` it returns 
  941.         ``True``.
  942.         
  943.         If the string is one of  ``False``, ``Off``, ``No``, or ``0`` it returns 
  944.         ``False``.
  945.         
  946.         ``as_bool`` is not case sensitive.
  947.         
  948.         Any other input will raise a ``ValueError``.
  949.         
  950.         >>> a = ConfigObj()
  951.         >>> a[\'a\'] = \'fish\'
  952.         >>> a.as_bool(\'a\')
  953.         Traceback (most recent call last):
  954.         ValueError: Value "fish" is neither True nor False
  955.         >>> a[\'b\'] = \'True\'
  956.         >>> a.as_bool(\'b\')
  957.         1
  958.         >>> a[\'b\'] = \'off\'
  959.         >>> a.as_bool(\'b\')
  960.         0
  961.         '''
  962.         val = self[key]
  963.         if val == True:
  964.             return True
  965.         if val == False:
  966.             return False
  967.         
  968.         try:
  969.             if not isinstance(val, StringTypes):
  970.                 raise KeyError()
  971.             isinstance(val, StringTypes)
  972.             return self.main._bools[val.lower()]
  973.         except KeyError:
  974.             val == False
  975.             val == False
  976.             val == True
  977.             raise ValueError('Value "%s" is neither True nor False' % val)
  978.         except:
  979.             val == False
  980.  
  981.  
  982.     
  983.     def as_int(self, key):
  984.         """
  985.         A convenience method which coerces the specified value to an integer.
  986.         
  987.         If the value is an invalid literal for ``int``, a ``ValueError`` will
  988.         be raised.
  989.         
  990.         >>> a = ConfigObj()
  991.         >>> a['a'] = 'fish'
  992.         >>> a.as_int('a')
  993.         Traceback (most recent call last):
  994.         ValueError: invalid literal for int(): fish
  995.         >>> a['b'] = '1'
  996.         >>> a.as_int('b')
  997.         1
  998.         >>> a['b'] = '3.2'
  999.         >>> a.as_int('b')
  1000.         Traceback (most recent call last):
  1001.         ValueError: invalid literal for int(): 3.2
  1002.         """
  1003.         return int(self[key])
  1004.  
  1005.     
  1006.     def as_float(self, key):
  1007.         """
  1008.         A convenience method which coerces the specified value to a float.
  1009.         
  1010.         If the value is an invalid literal for ``float``, a ``ValueError`` will
  1011.         be raised.
  1012.         
  1013.         >>> a = ConfigObj()
  1014.         >>> a['a'] = 'fish'
  1015.         >>> a.as_float('a')
  1016.         Traceback (most recent call last):
  1017.         ValueError: invalid literal for float(): fish
  1018.         >>> a['b'] = '1'
  1019.         >>> a.as_float('b')
  1020.         1.0
  1021.         >>> a['b'] = '3.2'
  1022.         >>> a.as_float('b')
  1023.         3.2000000000000002
  1024.         """
  1025.         return float(self[key])
  1026.  
  1027.     
  1028.     def restore_default(self, key):
  1029.         '''
  1030.         Restore (and return) default value for the specified key.
  1031.         
  1032.         This method will only work for a ConfigObj that was created
  1033.         with a configspec and has been validated.
  1034.         
  1035.         If there is no default value for this key, ``KeyError`` is raised.
  1036.         '''
  1037.         default = self.default_values[key]
  1038.         dict.__setitem__(self, key, default)
  1039.         if key not in self.defaults:
  1040.             self.defaults.append(key)
  1041.         
  1042.         return default
  1043.  
  1044.     
  1045.     def restore_defaults(self):
  1046.         """
  1047.         Recursively restore default values to all members
  1048.         that have them.
  1049.         
  1050.         This method will only work for a ConfigObj that was created
  1051.         with a configspec and has been validated.
  1052.         
  1053.         It doesn't delete or modify entries without default values.
  1054.         """
  1055.         for key in self.default_values:
  1056.             self.restore_default(key)
  1057.         
  1058.         for section in self.sections:
  1059.             self[section].restore_defaults()
  1060.         
  1061.  
  1062.  
  1063.  
  1064. class ConfigObj(Section):
  1065.     '''An object to read, create, and write config files.'''
  1066.     _keyword = re.compile('^ # line start\n        (\\s*)                   # indentation\n        (                       # keyword\n            (?:".*?")|          # double quotes\n            (?:\'.*?\')|          # single quotes\n            (?:[^\'"=].*?)       # no quotes\n        )\n        \\s*=\\s*                 # divider\n        (.*)                    # value (including list values and comments)\n        $   # line end\n        ', re.VERBOSE)
  1067.     _sectionmarker = re.compile('^\n        (\\s*)                     # 1: indentation\n        ((?:\\[\\s*)+)              # 2: section marker open\n        (                         # 3: section name open\n            (?:"\\s*\\S.*?\\s*")|    # at least one non-space with double quotes\n            (?:\'\\s*\\S.*?\\s*\')|    # at least one non-space with single quotes\n            (?:[^\'"\\s].*?)        # at least one non-space unquoted\n        )                         # section name close\n        ((?:\\s*\\])+)              # 4: section marker close\n        \\s*(\\#.*)?                # 5: optional comment\n        $', re.VERBOSE)
  1068.     _valueexp = re.compile('^\n        (?:\n            (?:\n                (\n                    (?:\n                        (?:\n                            (?:".*?")|              # double quotes\n                            (?:\'.*?\')|              # single quotes\n                            (?:[^\'",\\#][^,\\#]*?)    # unquoted\n                        )\n                        \\s*,\\s*                     # comma\n                    )*      # match all list items ending in a comma (if any)\n                )\n                (\n                    (?:".*?")|                      # double quotes\n                    (?:\'.*?\')|                      # single quotes\n                    (?:[^\'",\\#\\s][^,]*?)|           # unquoted\n                    (?:(?<!,))                      # Empty value\n                )?          # last item in a list - or string value\n            )|\n            (,)             # alternatively a single comma - empty list\n        )\n        \\s*(\\#.*)?          # optional comment\n        $', re.VERBOSE)
  1069.     _listvalueexp = re.compile('\n        (\n            (?:".*?")|          # double quotes\n            (?:\'.*?\')|          # single quotes\n            (?:[^\'",\\#].*?)       # unquoted\n        )\n        \\s*,\\s*                 # comma\n        ', re.VERBOSE)
  1070.     _nolistvalue = re.compile('^\n        (\n            (?:".*?")|          # double quotes\n            (?:\'.*?\')|          # single quotes\n            (?:[^\'"\\#].*?)|     # unquoted\n            (?:)                # Empty value\n        )\n        \\s*(\\#.*)?              # optional comment\n        $', re.VERBOSE)
  1071.     _single_line_single = re.compile("^'''(.*?)'''\\s*(#.*)?$")
  1072.     _single_line_double = re.compile('^"""(.*?)"""\\s*(#.*)?$')
  1073.     _multi_line_single = re.compile("^(.*?)'''\\s*(#.*)?$")
  1074.     _multi_line_double = re.compile('^(.*?)"""\\s*(#.*)?$')
  1075.     _triple_quote = {
  1076.         "'''": (_single_line_single, _multi_line_single),
  1077.         '"""': (_single_line_double, _multi_line_double) }
  1078.     _bools = {
  1079.         'yes': True,
  1080.         'no': False,
  1081.         'on': True,
  1082.         'off': False,
  1083.         '1': True,
  1084.         '0': False,
  1085.         'true': True,
  1086.         'false': False }
  1087.     
  1088.     def __init__(self, infile = None, options = None, **kwargs):
  1089.         '''
  1090.         Parse a config file or create a config file object.
  1091.         
  1092.         ``ConfigObj(infile=None, options=None, **kwargs)``
  1093.         '''
  1094.         Section.__init__(self, self, 0, self)
  1095.         if infile is None:
  1096.             infile = []
  1097.         
  1098.         if options is None:
  1099.             options = { }
  1100.         else:
  1101.             options = dict(options)
  1102.         options.update(kwargs)
  1103.         defaults = OPTION_DEFAULTS.copy()
  1104.         for entry in options:
  1105.             if entry not in defaults:
  1106.                 raise TypeError('Unrecognised option "%s".' % entry)
  1107.             entry not in defaults
  1108.         
  1109.         defaults.update(options)
  1110.         self._initialise(defaults)
  1111.         configspec = defaults['configspec']
  1112.         self._original_configspec = configspec
  1113.         self._load(infile, configspec)
  1114.  
  1115.     
  1116.     def _load(self, infile, configspec):
  1117.         if isinstance(infile, StringTypes):
  1118.             self.filename = infile
  1119.             if os.path.isfile(infile):
  1120.                 h = open(infile, 'rb')
  1121.                 if not h.read():
  1122.                     pass
  1123.                 infile = []
  1124.                 h.close()
  1125.             elif self.file_error:
  1126.                 raise IOError('Config file not found: "%s".' % self.filename)
  1127.             elif self.create_empty:
  1128.                 h = open(infile, 'w')
  1129.                 h.write('')
  1130.                 h.close()
  1131.             
  1132.             infile = []
  1133.         elif isinstance(infile, (list, tuple)):
  1134.             infile = list(infile)
  1135.         elif isinstance(infile, dict):
  1136.             if isinstance(infile, ConfigObj):
  1137.                 infile = infile.dict()
  1138.             
  1139.             for entry in infile:
  1140.                 self[entry] = infile[entry]
  1141.             
  1142.             del self._errors
  1143.             if configspec is not None:
  1144.                 self._handle_configspec(configspec)
  1145.             else:
  1146.                 self.configspec = None
  1147.             return None
  1148.         if hasattr(infile, 'read'):
  1149.             if not infile.read():
  1150.                 pass
  1151.             infile = []
  1152.         else:
  1153.             raise TypeError('infile must be a filename, file like object, or list of lines.')
  1154.         self._parse(infile)
  1155.         if self._errors:
  1156.             info = 'at line %s.' % self._errors[0].line_number
  1157.             if len(self._errors) > 1:
  1158.                 msg = 'Parsing failed with several errors.\nFirst error %s' % info
  1159.                 error = ConfigObjError(msg)
  1160.             else:
  1161.                 error = self._errors[0]
  1162.             error.errors = self._errors
  1163.             error.config = self
  1164.             raise error
  1165.         self._errors
  1166.         del self._errors
  1167.         if configspec is None:
  1168.             self.configspec = None
  1169.         else:
  1170.             self._handle_configspec(configspec)
  1171.  
  1172.     
  1173.     def _initialise(self, options = None):
  1174.         if options is None:
  1175.             options = OPTION_DEFAULTS
  1176.         
  1177.         self.filename = None
  1178.         self._errors = []
  1179.         self.raise_errors = options['raise_errors']
  1180.         self.interpolation = options['interpolation']
  1181.         self.list_values = options['list_values']
  1182.         self.create_empty = options['create_empty']
  1183.         self.file_error = options['file_error']
  1184.         self.stringify = options['stringify']
  1185.         self.indent_type = options['indent_type']
  1186.         self.encoding = options['encoding']
  1187.         self.default_encoding = options['default_encoding']
  1188.         self.BOM = False
  1189.         self.newlines = None
  1190.         self.write_empty_values = options['write_empty_values']
  1191.         self.unrepr = options['unrepr']
  1192.         self.initial_comment = []
  1193.         self.final_comment = []
  1194.         self.configspec = { }
  1195.         Section._initialise(self)
  1196.  
  1197.     
  1198.     def __repr__(self):
  1199.         return [] % []([ '%s: %s' % (repr(key), repr(self[key])) for key in self.scalars + self.sections ])
  1200.  
  1201.     
  1202.     def _handle_bom(self, infile):
  1203.         """
  1204.         Handle any BOM, and decode if necessary.
  1205.         
  1206.         If an encoding is specified, that *must* be used - but the BOM should
  1207.         still be removed (and the BOM attribute set).
  1208.         
  1209.         (If the encoding is wrongly specified, then a BOM for an alternative
  1210.         encoding won't be discovered or removed.)
  1211.         
  1212.         If an encoding is not specified, UTF8 or UTF16 BOM will be detected and
  1213.         removed. The BOM attribute will be set. UTF16 will be decoded to
  1214.         unicode.
  1215.         
  1216.         NOTE: This method must not be called with an empty ``infile``.
  1217.         
  1218.         Specifying the *wrong* encoding is likely to cause a
  1219.         ``UnicodeDecodeError``.
  1220.         
  1221.         ``infile`` must always be returned as a list of lines, but may be
  1222.         passed in as a single string.
  1223.         """
  1224.         if self.encoding is not None and self.encoding.lower() not in BOM_LIST:
  1225.             return self._decode(infile, self.encoding)
  1226.         if isinstance(infile, (list, tuple)):
  1227.             line = infile[0]
  1228.         else:
  1229.             line = infile
  1230.         if self.encoding is not None:
  1231.             enc = BOM_LIST[self.encoding.lower()]
  1232.             if enc == 'utf_16':
  1233.                 for encoding, final_encoding in BOMS.items():
  1234.                     if not final_encoding:
  1235.                         continue
  1236.                     
  1237.                     if infile.startswith(BOM):
  1238.                         return self._decode(infile, encoding)
  1239.                 
  1240.                 return self._decode(infile, self.encoding)
  1241.             BOM = BOM_SET[enc]
  1242.             if not line.startswith(BOM):
  1243.                 return self._decode(infile, self.encoding)
  1244.             newline = line[len(BOM):]
  1245.             self.BOM = True
  1246.             return self._decode(infile, self.encoding)
  1247.         for encoding, final_encoding in BOMS.items():
  1248.             if not line.startswith(BOM):
  1249.                 continue
  1250.                 continue
  1251.             self.encoding = final_encoding
  1252.             if not final_encoding:
  1253.                 self.BOM = True
  1254.                 newline = line[len(BOM):]
  1255.                 if isinstance(infile, (list, tuple)):
  1256.                     infile[0] = newline
  1257.                 else:
  1258.                     infile = newline
  1259.                 if isinstance(infile, StringTypes):
  1260.                     return infile.splitlines(True)
  1261.                 return infile
  1262.             final_encoding
  1263.             return self._decode(infile, encoding)
  1264.         
  1265.         if isinstance(infile, StringTypes):
  1266.             return infile.splitlines(True)
  1267.         return infile
  1268.  
  1269.     
  1270.     def _a_to_u(self, aString):
  1271.         '''Decode ASCII strings to unicode if a self.encoding is specified.'''
  1272.         if self.encoding:
  1273.             return aString.decode('ascii')
  1274.         return aString
  1275.  
  1276.     
  1277.     def _decode(self, infile, encoding):
  1278.         '''
  1279.         Decode infile to unicode. Using the specified encoding.
  1280.         
  1281.         if is a string, it also needs converting to a list.
  1282.         '''
  1283.         if isinstance(infile, StringTypes):
  1284.             return infile.decode(encoding).splitlines(True)
  1285.         for i, line in enumerate(infile):
  1286.             if not isinstance(line, unicode):
  1287.                 infile[i] = line.decode(encoding)
  1288.                 continue
  1289.             isinstance(infile, StringTypes)
  1290.         
  1291.         return infile
  1292.  
  1293.     
  1294.     def _decode_element(self, line):
  1295.         '''Decode element to unicode if necessary.'''
  1296.         if not self.encoding:
  1297.             return line
  1298.         if isinstance(line, str) and self.default_encoding:
  1299.             return line.decode(self.default_encoding)
  1300.         return line
  1301.  
  1302.     
  1303.     def _str(self, value):
  1304.         '''
  1305.         Used by ``stringify`` within validate, to turn non-string values
  1306.         into strings.
  1307.         '''
  1308.         if not isinstance(value, StringTypes):
  1309.             return str(value)
  1310.         return value
  1311.  
  1312.     
  1313.     def _parse(self, infile):
  1314.         '''Actually parse the config file.'''
  1315.         temp_list_values = self.list_values
  1316.         if self.unrepr:
  1317.             self.list_values = False
  1318.         
  1319.         comment_list = []
  1320.         done_start = False
  1321.         this_section = self
  1322.         maxline = len(infile) - 1
  1323.         cur_index = -1
  1324.         reset_comment = False
  1325.         while cur_index < maxline:
  1326.             if reset_comment:
  1327.                 comment_list = []
  1328.             
  1329.             cur_index += 1
  1330.             line = infile[cur_index]
  1331.             sline = line.strip()
  1332.             if not sline or sline.startswith('#'):
  1333.                 reset_comment = False
  1334.                 comment_list.append(line)
  1335.                 continue
  1336.             
  1337.             if not done_start:
  1338.                 self.initial_comment = comment_list
  1339.                 comment_list = []
  1340.                 done_start = True
  1341.             
  1342.             reset_comment = True
  1343.             mat = self._sectionmarker.match(line)
  1344.             if mat is not None:
  1345.                 (indent, sect_open, sect_name, sect_close, comment) = mat.groups()
  1346.                 if indent and self.indent_type is None:
  1347.                     self.indent_type = indent
  1348.                 
  1349.                 cur_depth = sect_open.count('[')
  1350.                 if cur_depth != sect_close.count(']'):
  1351.                     self._handle_error('Cannot compute the section depth at line %s.', NestingError, infile, cur_index)
  1352.                     continue
  1353.                 
  1354.                 if cur_depth < this_section.depth:
  1355.                     
  1356.                     try:
  1357.                         parent = self._match_depth(this_section, cur_depth).parent
  1358.                     except SyntaxError:
  1359.                         self._handle_error('Cannot compute nesting level at line %s.', NestingError, infile, cur_index)
  1360.                         continue
  1361.                     except:
  1362.                         None<EXCEPTION MATCH>SyntaxError
  1363.                     
  1364.  
  1365.                 None<EXCEPTION MATCH>SyntaxError
  1366.                 if cur_depth == this_section.depth:
  1367.                     parent = this_section.parent
  1368.                 elif cur_depth == this_section.depth + 1:
  1369.                     parent = this_section
  1370.                 else:
  1371.                     self._handle_error('Section too nested at line %s.', NestingError, infile, cur_index)
  1372.                 sect_name = self._unquote(sect_name)
  1373.                 if parent.has_key(sect_name):
  1374.                     self._handle_error('Duplicate section name at line %s.', DuplicateError, infile, cur_index)
  1375.                     continue
  1376.                 
  1377.                 this_section = Section(parent, cur_depth, self, name = sect_name)
  1378.                 parent[sect_name] = this_section
  1379.                 parent.inline_comments[sect_name] = comment
  1380.                 parent.comments[sect_name] = comment_list
  1381.                 continue
  1382.             
  1383.             mat = self._keyword.match(line)
  1384.             if mat is None:
  1385.                 self._handle_error('Invalid line at line "%s".', ParseError, infile, cur_index)
  1386.                 continue
  1387.             (indent, key, value) = mat.groups()
  1388.             if indent and self.indent_type is None:
  1389.                 self.indent_type = indent
  1390.             
  1391.             None if value[:3] in ('"""', "'''") else None<EXCEPTION MATCH>Exception
  1392.             
  1393.             try:
  1394.                 (value, comment) = self._handle_value(value)
  1395.             except SyntaxError:
  1396.                 self._handle_error('Parse error in value at line %s.', ParseError, infile, cur_index)
  1397.                 continue
  1398.  
  1399.             key = self._unquote(key)
  1400.             if this_section.has_key(key):
  1401.                 self._handle_error('Duplicate keyword name at line %s.', DuplicateError, infile, cur_index)
  1402.                 continue
  1403.             
  1404.             this_section.__setitem__(key, value, unrepr = True)
  1405.             this_section.inline_comments[key] = comment
  1406.             this_section.comments[key] = comment_list
  1407.             continue
  1408.         if self.indent_type is None:
  1409.             self.indent_type = ''
  1410.         
  1411.         if not self and not (self.initial_comment):
  1412.             self.initial_comment = comment_list
  1413.         elif not reset_comment:
  1414.             self.final_comment = comment_list
  1415.         
  1416.         self.list_values = temp_list_values
  1417.  
  1418.     
  1419.     def _match_depth(self, sect, depth):
  1420.         '''
  1421.         Given a section and a depth level, walk back through the sections
  1422.         parents to see if the depth level matches a previous section.
  1423.         
  1424.         Return a reference to the right section,
  1425.         or raise a SyntaxError.
  1426.         '''
  1427.         while depth < sect.depth:
  1428.             if sect is sect.parent:
  1429.                 raise SyntaxError()
  1430.             sect is sect.parent
  1431.             sect = sect.parent
  1432.         if sect.depth == depth:
  1433.             return sect
  1434.         raise SyntaxError()
  1435.  
  1436.     
  1437.     def _handle_error(self, text, ErrorClass, infile, cur_index):
  1438.         '''
  1439.         Handle an error according to the error settings.
  1440.         
  1441.         Either raise the error or store it.
  1442.         The error will have occured at ``cur_index``
  1443.         '''
  1444.         line = infile[cur_index]
  1445.         cur_index += 1
  1446.         message = text % cur_index
  1447.         error = ErrorClass(message, cur_index, line)
  1448.         if self.raise_errors:
  1449.             raise error
  1450.         self.raise_errors
  1451.         self._errors.append(error)
  1452.  
  1453.     
  1454.     def _unquote(self, value):
  1455.         '''Return an unquoted version of a value'''
  1456.         if value[0] == value[-1] and value[0] in ('"', "'"):
  1457.             value = value[1:-1]
  1458.         
  1459.         return value
  1460.  
  1461.     
  1462.     def _quote(self, value, multiline = True):
  1463.         """
  1464.         Return a safely quoted version of a value.
  1465.         
  1466.         Raise a ConfigObjError if the value cannot be safely quoted.
  1467.         If multiline is ``True`` (default) then use triple quotes
  1468.         if necessary.
  1469.         
  1470.         Don't quote values that don't need it.
  1471.         Recursively quote members of a list and return a comma joined list.
  1472.         Multiline is ``False`` for lists.
  1473.         Obey list syntax for empty and single member lists.
  1474.         
  1475.         If ``list_values=False`` then the value is only quoted if it contains
  1476.         a ``
  1477. `` (is multiline) or '#'.
  1478.         
  1479.         If ``write_empty_values`` is set, and the value is an empty string, it
  1480.         won't be quoted.
  1481.         """
  1482.         if multiline and self.write_empty_values and value == '':
  1483.             return ''
  1484.         isinstance(value, (list, tuple)) if multiline and isinstance(value, (list, tuple)) else self.stringify
  1485.         no_lists_no_quotes = value if not value else '#' not in value
  1486.         if multiline:
  1487.             if not "'" in value or '"' in value:
  1488.                 pass
  1489.         need_triple = '\n' in value
  1490.         if multiline and not need_triple and "'" in value and '"' in value:
  1491.             pass
  1492.         hash_triple_quote = '#' in value
  1493.         if no_lists_no_quotes or not need_triple:
  1494.             pass
  1495.         check_for_single = not hash_triple_quote
  1496.         if check_for_single:
  1497.             if not self.list_values:
  1498.                 quot = noquot
  1499.             elif '\n' in value:
  1500.                 raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
  1501.             elif value[0] not in wspace_plus and value[-1] not in wspace_plus and ',' not in value:
  1502.                 quot = noquot
  1503.             else:
  1504.                 quot = self._get_single_quote(value)
  1505.         else:
  1506.             quot = self._get_triple_quote(value)
  1507.         if quot == noquot and '#' in value and self.list_values:
  1508.             quot = self._get_single_quote(value)
  1509.         
  1510.         return quot % value
  1511.  
  1512.     
  1513.     def _get_single_quote(self, value):
  1514.         if "'" in value and '"' in value:
  1515.             raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
  1516.         '"' in value
  1517.         if '"' in value:
  1518.             quot = squot
  1519.         else:
  1520.             quot = dquot
  1521.         return quot
  1522.  
  1523.     
  1524.     def _get_triple_quote(self, value):
  1525.         if value.find('"""') != -1 and value.find("'''") != -1:
  1526.             raise ConfigObjError('Value "%s" cannot be safely quoted.' % value)
  1527.         value.find("'''") != -1
  1528.         if value.find('"""') == -1:
  1529.             quot = tdquot
  1530.         else:
  1531.             quot = tsquot
  1532.         return quot
  1533.  
  1534.     
  1535.     def _handle_value(self, value):
  1536.         '''
  1537.         Given a value string, unquote, remove comment,
  1538.         handle lists. (including empty and single member lists)
  1539.         '''
  1540.         if not self.list_values:
  1541.             mat = self._nolistvalue.match(value)
  1542.             if mat is None:
  1543.                 raise SyntaxError()
  1544.             mat is None
  1545.             return mat.groups()
  1546.         mat = self._valueexp.match(value)
  1547.         if mat is None:
  1548.             raise SyntaxError()
  1549.         mat is None
  1550.         (list_values, single, empty_list, comment) = mat.groups()
  1551.         if list_values == '' and single is None:
  1552.             raise SyntaxError()
  1553.         single is None
  1554.         if empty_list is not None:
  1555.             return ([], comment)
  1556.         if single is not None:
  1557.             single = empty_list is not None if list_values and not single else '""'
  1558.             single = self._unquote(single)
  1559.         
  1560.         if list_values == '':
  1561.             return (single, comment)
  1562.         the_list = self._listvalueexp.findall(list_values)
  1563.         the_list = [ self._unquote(val) for val in the_list ]
  1564.         return (the_list, comment)
  1565.  
  1566.     
  1567.     def _multiline(self, value, infile, cur_index, maxline):
  1568.         '''Extract the value, where we are in a multiline situation.'''
  1569.         quot = value[:3]
  1570.         newvalue = value[3:]
  1571.         single_line = self._triple_quote[quot][0]
  1572.         multi_line = self._triple_quote[quot][1]
  1573.         mat = single_line.match(value)
  1574.         if mat is not None:
  1575.             retval = list(mat.groups())
  1576.             retval.append(cur_index)
  1577.             return retval
  1578.         if newvalue.find(quot) != -1:
  1579.             raise SyntaxError()
  1580.         newvalue.find(quot) != -1
  1581.         while cur_index < maxline:
  1582.             cur_index += 1
  1583.             newvalue += '\n'
  1584.             line = infile[cur_index]
  1585.             if line.find(quot) == -1:
  1586.                 newvalue += line
  1587.                 continue
  1588.             mat is not None
  1589.             break
  1590.         raise SyntaxError()
  1591.         mat = multi_line.match(line)
  1592.         if mat is None:
  1593.             raise SyntaxError()
  1594.         mat is None
  1595.         (value, comment) = mat.groups()
  1596.         return (newvalue + value, comment, cur_index)
  1597.  
  1598.     
  1599.     def _handle_configspec(self, configspec):
  1600.         '''Parse the configspec.'''
  1601.         if not isinstance(configspec, ConfigObj):
  1602.             
  1603.             try:
  1604.                 configspec = ConfigObj(configspec, raise_errors = True, file_error = True, list_values = False)
  1605.             except ConfigObjError:
  1606.                 e = None
  1607.                 raise ConfigspecError('Parsing configspec failed: %s' % e)
  1608.             except IOError:
  1609.                 e = None
  1610.                 raise IOError('Reading configspec failed: %s' % e)
  1611.             except:
  1612.                 None<EXCEPTION MATCH>ConfigObjError
  1613.             
  1614.  
  1615.         None<EXCEPTION MATCH>ConfigObjError
  1616.         self._set_configspec_value(configspec, self)
  1617.  
  1618.     
  1619.     def _set_configspec_value(self, configspec, section):
  1620.         '''Used to recursively set configspec values.'''
  1621.         if '__many__' in configspec.sections:
  1622.             section.configspec['__many__'] = configspec['__many__']
  1623.             if len(configspec.sections) > 1:
  1624.                 raise RepeatSectionError()
  1625.             len(configspec.sections) > 1
  1626.         
  1627.         if hasattr(configspec, 'initial_comment'):
  1628.             section._configspec_initial_comment = configspec.initial_comment
  1629.             section._configspec_final_comment = configspec.final_comment
  1630.             section._configspec_encoding = configspec.encoding
  1631.             section._configspec_BOM = configspec.BOM
  1632.             section._configspec_newlines = configspec.newlines
  1633.             section._configspec_indent_type = configspec.indent_type
  1634.         
  1635.         for entry in configspec.scalars:
  1636.             section._configspec_comments[entry] = configspec.comments[entry]
  1637.             section._configspec_inline_comments[entry] = configspec.inline_comments[entry]
  1638.             section.configspec[entry] = configspec[entry]
  1639.             section._order.append(entry)
  1640.         
  1641.         for entry in configspec.sections:
  1642.             if entry == '__many__':
  1643.                 continue
  1644.             
  1645.             section._cs_section_comments[entry] = configspec.comments[entry]
  1646.             section._cs_section_inline_comments[entry] = configspec.inline_comments[entry]
  1647.             if not section.has_key(entry):
  1648.                 section[entry] = { }
  1649.             
  1650.             self._set_configspec_value(configspec[entry], section[entry])
  1651.         
  1652.  
  1653.     
  1654.     def _handle_repeat(self, section, configspec):
  1655.         '''Dynamically assign configspec for repeated section.'''
  1656.         
  1657.         try:
  1658.             section_keys = configspec.sections
  1659.             scalar_keys = configspec.scalars
  1660.         except AttributeError:
  1661.             section_keys = _[1]
  1662.             scalar_keys = _[2]
  1663.         except:
  1664.             []
  1665.  
  1666.         if '__many__' in section_keys and len(section_keys) > 1:
  1667.             raise RepeatSectionError()
  1668.         len(section_keys) > 1
  1669.         scalars = { }
  1670.         sections = { }
  1671.         for entry in scalar_keys:
  1672.             val = configspec[entry]
  1673.             scalars[entry] = val
  1674.         
  1675.         for entry in section_keys:
  1676.             val = configspec[entry]
  1677.             sections[entry] = val
  1678.         
  1679.         section.configspec = scalars
  1680.         for entry in sections:
  1681.             self._handle_repeat(section[entry], sections[entry])
  1682.         
  1683.  
  1684.     
  1685.     def _write_line(self, indent_string, entry, this_entry, comment):
  1686.         '''Write an individual line, for the write method'''
  1687.         if not self.unrepr:
  1688.             val = self._decode_element(self._quote(this_entry))
  1689.         else:
  1690.             val = repr(this_entry)
  1691.         return '%s%s%s%s%s' % (indent_string, self._decode_element(self._quote(entry, multiline = False)), self._a_to_u(' = '), val, self._decode_element(comment))
  1692.  
  1693.     
  1694.     def _write_marker(self, indent_string, depth, entry, comment):
  1695.         '''Write a section marker line'''
  1696.         return '%s%s%s%s%s' % (indent_string, self._a_to_u('[' * depth), self._quote(self._decode_element(entry), multiline = False), self._a_to_u(']' * depth), self._decode_element(comment))
  1697.  
  1698.     
  1699.     def _handle_comment(self, comment):
  1700.         '''Deal with a comment.'''
  1701.         if not comment:
  1702.             return ''
  1703.         start = self.indent_type
  1704.         if not comment.startswith('#'):
  1705.             start += self._a_to_u(' # ')
  1706.         
  1707.         return start + comment
  1708.  
  1709.     
  1710.     def write(self, outfile = None, section = None):
  1711.         """
  1712.         Write the current ConfigObj as a file
  1713.         
  1714.         tekNico: FIXME: use StringIO instead of real files
  1715.         
  1716.         >>> filename = a.filename
  1717.         >>> a.filename = 'test.ini'
  1718.         >>> a.write()
  1719.         >>> a.filename = filename
  1720.         >>> a == ConfigObj('test.ini', raise_errors=True)
  1721.         1
  1722.         """
  1723.         if self.indent_type is None:
  1724.             self.indent_type = DEFAULT_INDENT_TYPE
  1725.         
  1726.         out = []
  1727.         cs = self._a_to_u('#')
  1728.         csp = self._a_to_u('# ')
  1729.         if section is None:
  1730.             int_val = self.interpolation
  1731.             self.interpolation = False
  1732.             section = self
  1733.             for line in self.initial_comment:
  1734.                 line = self._decode_element(line)
  1735.                 stripped_line = line.strip()
  1736.                 if stripped_line and not stripped_line.startswith(cs):
  1737.                     line = csp + line
  1738.                 
  1739.                 out.append(line)
  1740.             
  1741.         
  1742.         indent_string = self.indent_type * section.depth
  1743.         for entry in section.scalars + section.sections:
  1744.             if entry in section.defaults:
  1745.                 continue
  1746.             
  1747.             for comment_line in section.comments[entry]:
  1748.                 comment_line = self._decode_element(comment_line.lstrip())
  1749.                 if comment_line and not comment_line.startswith(cs):
  1750.                     comment_line = csp + comment_line
  1751.                 
  1752.                 out.append(indent_string + comment_line)
  1753.             
  1754.             this_entry = section[entry]
  1755.             comment = self._handle_comment(section.inline_comments[entry])
  1756.             if isinstance(this_entry, dict):
  1757.                 out.append(self._write_marker(indent_string, this_entry.depth, entry, comment))
  1758.                 out.extend(self.write(section = this_entry))
  1759.                 continue
  1760.             out.append(self._write_line(indent_string, entry, this_entry, comment))
  1761.         
  1762.         if section is self:
  1763.             for line in self.final_comment:
  1764.                 line = self._decode_element(line)
  1765.                 stripped_line = line.strip()
  1766.                 if stripped_line and not stripped_line.startswith(cs):
  1767.                     line = csp + line
  1768.                 
  1769.                 out.append(line)
  1770.             
  1771.             self.interpolation = int_val
  1772.         
  1773.         if section is not self:
  1774.             return out
  1775.         newline = outfile is None if self.filename is None and outfile is None else os.linesep
  1776.         output = self._a_to_u(newline).join(out)
  1777.         if self.encoding:
  1778.             output = output.encode(self.encoding)
  1779.         
  1780.         if self.BOM:
  1781.             if self.encoding is None or match_utf8(self.encoding):
  1782.                 output = BOM_UTF8 + output
  1783.             
  1784.         if not output.endswith(newline):
  1785.             output += newline
  1786.         
  1787.         if outfile is not None:
  1788.             outfile.write(output)
  1789.         else:
  1790.             h = open(self.filename, 'wb')
  1791.             h.write(output)
  1792.             h.close()
  1793.  
  1794.     
  1795.     def validate(self, validator, preserve_errors = False, copy = False, section = None):
  1796.         '''
  1797.         Test the ConfigObj against a configspec.
  1798.         
  1799.         It uses the ``validator`` object from *validate.py*.
  1800.         
  1801.         To run ``validate`` on the current ConfigObj, call: ::
  1802.         
  1803.             test = config.validate(validator)
  1804.         
  1805.         (Normally having previously passed in the configspec when the ConfigObj
  1806.         was created - you can dynamically assign a dictionary of checks to the
  1807.         ``configspec`` attribute of a section though).
  1808.         
  1809.         It returns ``True`` if everything passes, or a dictionary of
  1810.         pass/fails (True/False). If every member of a subsection passes, it
  1811.         will just have the value ``True``. (It also returns ``False`` if all
  1812.         members fail).
  1813.         
  1814.         In addition, it converts the values from strings to their native
  1815.         types if their checks pass (and ``stringify`` is set).
  1816.         
  1817.         If ``preserve_errors`` is ``True`` (``False`` is default) then instead
  1818.         of a marking a fail with a ``False``, it will preserve the actual
  1819.         exception object. This can contain info about the reason for failure.
  1820.         For example the ``VdtValueTooSmallError`` indicates that the value
  1821.         supplied was too small. If a value (or section) is missing it will
  1822.         still be marked as ``False``.
  1823.         
  1824.         You must have the validate module to use ``preserve_errors=True``.
  1825.         
  1826.         You can then use the ``flatten_errors`` function to turn your nested
  1827.         results dictionary into a flattened list of failures - useful for
  1828.         displaying meaningful error messages.
  1829.         '''
  1830.         if section is None:
  1831.             if self.configspec is None:
  1832.                 raise ValueError('No configspec supplied.')
  1833.             self.configspec is None
  1834.             if preserve_errors:
  1835.                 VdtMissingValue = VdtMissingValue
  1836.                 import validate
  1837.                 self._vdtMissingValue = VdtMissingValue
  1838.             
  1839.             section = self
  1840.         
  1841.         spec_section = section.configspec
  1842.         if copy and hasattr(section, '_configspec_initial_comment'):
  1843.             section.initial_comment = section._configspec_initial_comment
  1844.             section.final_comment = section._configspec_final_comment
  1845.             section.encoding = section._configspec_encoding
  1846.             section.BOM = section._configspec_BOM
  1847.             section.newlines = section._configspec_newlines
  1848.             section.indent_type = section._configspec_indent_type
  1849.         
  1850.         if '__many__' in section.configspec:
  1851.             many = spec_section['__many__']
  1852.             for entry in section.sections:
  1853.                 self._handle_repeat(section[entry], many)
  1854.             
  1855.         
  1856.         out = { }
  1857.         ret_true = True
  1858.         ret_false = True
  1859.         order = _[1]
  1860.         [] += _[2]
  1861.         for entry in order:
  1862.             
  1863.             try:
  1864.                 check = validator.check(spec_section[entry], val, missing = missing)
  1865.             except validator.baseErrorClass:
  1866.                 None if entry not in section.scalars or entry in section.defaults else []
  1867.                 e = None if entry not in section.scalars or entry in section.defaults else []
  1868.                 if not preserve_errors or isinstance(e, self._vdtMissingValue):
  1869.                     out[entry] = False
  1870.                 else:
  1871.                     out[entry] = e
  1872.                     ret_false = False
  1873.                 ret_true = False
  1874.                 continue
  1875.  
  1876.             
  1877.             try:
  1878.                 section.default_values.pop(entry, None)
  1879.             except AttributeError:
  1880.                 None if entry not in section.scalars or entry in section.defaults else []
  1881.                 None if entry not in section.scalars or entry in section.defaults else []
  1882.                 
  1883.                 try:
  1884.                     del section.default_values[entry]
  1885.                 except KeyError:
  1886.                     pass
  1887.                 except:
  1888.                     None<EXCEPTION MATCH>KeyError
  1889.                 
  1890.  
  1891.                 None<EXCEPTION MATCH>KeyError
  1892.  
  1893.             if hasattr(validator, 'get_default_value'):
  1894.                 
  1895.                 try:
  1896.                     section.default_values[entry] = validator.get_default_value(spec_section[entry])
  1897.                 except KeyError:
  1898.                     None if entry not in section.scalars or entry in section.defaults else []
  1899.                     None if entry not in section.scalars or entry in section.defaults else []
  1900.                 except:
  1901.                     None if entry not in section.scalars or entry in section.defaults else []<EXCEPTION MATCH>KeyError
  1902.                 
  1903.  
  1904.             None if entry not in section.scalars or entry in section.defaults else []
  1905.             ret_false = False
  1906.             out[entry] = True
  1907.             if self.stringify or missing:
  1908.                 if not self.stringify:
  1909.                     if isinstance(check, (list, tuple)):
  1910.                         check = [ self._str(item) for item in check ]
  1911.                     elif missing and check is None:
  1912.                         check = ''
  1913.                     else:
  1914.                         check = self._str(check)
  1915.                 
  1916.                 if check != val or missing:
  1917.                     section[entry] = check
  1918.                 
  1919.             
  1920.             if not copy and missing and entry not in section.defaults:
  1921.                 section.defaults.append(entry)
  1922.                 continue
  1923.         
  1924.         for entry in section.sections:
  1925.             if section is self and entry == 'DEFAULT':
  1926.                 continue
  1927.             
  1928.             if copy:
  1929.                 section.comments[entry] = section._cs_section_comments.get(entry, [])
  1930.                 section.inline_comments[entry] = section._cs_section_inline_comments.get(entry, '')
  1931.             
  1932.             check = self.validate(validator, preserve_errors = preserve_errors, copy = copy, section = section[entry])
  1933.             out[entry] = check
  1934.             if check == False:
  1935.                 ret_true = False
  1936.                 continue
  1937.             if check == True:
  1938.                 ret_false = False
  1939.                 continue
  1940.             ret_true = False
  1941.             ret_false = False
  1942.         
  1943.         if ret_true:
  1944.             return True
  1945.         if ret_false:
  1946.             return False
  1947.         return out
  1948.  
  1949.     
  1950.     def reset(self):
  1951.         """Clear ConfigObj instance and restore to 'freshly created' state."""
  1952.         self.clear()
  1953.         self._initialise()
  1954.         self.configspec = None
  1955.         self._original_configspec = None
  1956.  
  1957.     
  1958.     def reload(self):
  1959.         """
  1960.         Reload a ConfigObj from file.
  1961.         
  1962.         This method raises a ``ReloadError`` if the ConfigObj doesn't have
  1963.         a filename attribute pointing to a file.
  1964.         """
  1965.         if not isinstance(self.filename, StringTypes):
  1966.             raise ReloadError()
  1967.         isinstance(self.filename, StringTypes)
  1968.         filename = self.filename
  1969.         current_options = { }
  1970.         for entry in OPTION_DEFAULTS:
  1971.             if entry == 'configspec':
  1972.                 continue
  1973.             
  1974.             current_options[entry] = getattr(self, entry)
  1975.         
  1976.         configspec = self._original_configspec
  1977.         current_options['configspec'] = configspec
  1978.         self.clear()
  1979.         self._initialise(current_options)
  1980.         self._load(filename, configspec)
  1981.  
  1982.  
  1983.  
  1984. class SimpleVal(object):
  1985.     '''
  1986.     A simple validator.
  1987.     Can be used to check that all members expected are present.
  1988.     
  1989.     To use it, provide a configspec with all your members in (the value given
  1990.     will be ignored). Pass an instance of ``SimpleVal`` to the ``validate``
  1991.     method of your ``ConfigObj``. ``validate`` will return ``True`` if all
  1992.     members are present, or a dictionary with True/False meaning
  1993.     present/missing. (Whole missing sections will be replaced with ``False``)
  1994.     '''
  1995.     
  1996.     def __init__(self):
  1997.         self.baseErrorClass = ConfigObjError
  1998.  
  1999.     
  2000.     def check(self, check, member, missing = False):
  2001.         '''A dummy check method, always returns the value unchanged.'''
  2002.         if missing:
  2003.             raise self.baseErrorClass()
  2004.         missing
  2005.         return member
  2006.  
  2007.  
  2008.  
  2009. def flatten_errors(cfg, res, levels = None, results = None):
  2010.     '''
  2011.     An example function that will turn a nested dictionary of results
  2012.     (as returned by ``ConfigObj.validate``) into a flat list.
  2013.     
  2014.     ``cfg`` is the ConfigObj instance being checked, ``res`` is the results
  2015.     dictionary returned by ``validate``.
  2016.     
  2017.     (This is a recursive function, so you shouldn\'t use the ``levels`` or
  2018.     ``results`` arguments - they are used by the function.
  2019.     
  2020.     Returns a list of keys that failed. Each member of the list is a tuple :
  2021.     ::
  2022.     
  2023.         ([list of sections...], key, result)
  2024.     
  2025.     If ``validate`` was called with ``preserve_errors=False`` (the default)
  2026.     then ``result`` will always be ``False``.
  2027.  
  2028.     *list of sections* is a flattened list of sections that the key was found
  2029.     in.
  2030.     
  2031.     If the section was missing then key will be ``None``.
  2032.     
  2033.     If the value (or section) was missing then ``result`` will be ``False``.
  2034.     
  2035.     If ``validate`` was called with ``preserve_errors=True`` and a value
  2036.     was present, but failed the check, then ``result`` will be the exception
  2037.     object returned. You can use this as a string that describes the failure.
  2038.     
  2039.     For example *The value "3" is of the wrong type*.
  2040.     
  2041.     >>> import validate
  2042.     >>> vtor = validate.Validator()
  2043.     >>> my_ini = \'\'\'
  2044.     ...     option1 = True
  2045.     ...     [section1]
  2046.     ...     option1 = True
  2047.     ...     [section2]
  2048.     ...     another_option = Probably
  2049.     ...     [section3]
  2050.     ...     another_option = True
  2051.     ...     [[section3b]]
  2052.     ...     value = 3
  2053.     ...     value2 = a
  2054.     ...     value3 = 11
  2055.     ...     \'\'\'
  2056.     >>> my_cfg = \'\'\'
  2057.     ...     option1 = boolean()
  2058.     ...     option2 = boolean()
  2059.     ...     option3 = boolean(default=Bad_value)
  2060.     ...     [section1]
  2061.     ...     option1 = boolean()
  2062.     ...     option2 = boolean()
  2063.     ...     option3 = boolean(default=Bad_value)
  2064.     ...     [section2]
  2065.     ...     another_option = boolean()
  2066.     ...     [section3]
  2067.     ...     another_option = boolean()
  2068.     ...     [[section3b]]
  2069.     ...     value = integer
  2070.     ...     value2 = integer
  2071.     ...     value3 = integer(0, 10)
  2072.     ...         [[[section3b-sub]]]
  2073.     ...         value = string
  2074.     ...     [section4]
  2075.     ...     another_option = boolean()
  2076.     ...     \'\'\'
  2077.     >>> cs = my_cfg.split(\'\\n\')
  2078.     >>> ini = my_ini.split(\'\\n\')
  2079.     >>> cfg = ConfigObj(ini, configspec=cs)
  2080.     >>> res = cfg.validate(vtor, preserve_errors=True)
  2081.     >>> errors = []
  2082.     >>> for entry in flatten_errors(cfg, res):
  2083.     ...     section_list, key, error = entry
  2084.     ...     section_list.insert(0, \'[root]\')
  2085.     ...     if key is not None:
  2086.     ...        section_list.append(key)
  2087.     ...     else:
  2088.     ...         section_list.append(\'[missing]\')
  2089.     ...     section_string = \', \'.join(section_list)
  2090.     ...     errors.append((section_string, \' = \', error))
  2091.     >>> errors.sort()
  2092.     >>> for entry in errors:
  2093.     ...     print entry[0], entry[1], (entry[2] or 0)
  2094.     [root], option2  =  0
  2095.     [root], option3  =  the value "Bad_value" is of the wrong type.
  2096.     [root], section1, option2  =  0
  2097.     [root], section1, option3  =  the value "Bad_value" is of the wrong type.
  2098.     [root], section2, another_option  =  the value "Probably" is of the wrong type.
  2099.     [root], section3, section3b, section3b-sub, [missing]  =  0
  2100.     [root], section3, section3b, value2  =  the value "a" is of the wrong type.
  2101.     [root], section3, section3b, value3  =  the value "11" is too big.
  2102.     [root], section4, [missing]  =  0
  2103.     '''
  2104.     if levels is None:
  2105.         levels = []
  2106.         results = []
  2107.     
  2108.     if res is True:
  2109.         return results
  2110.     if res is False:
  2111.         results.append((levels[:], None, False))
  2112.         if levels:
  2113.             levels.pop()
  2114.         
  2115.         return results
  2116.     for key, val in res.items():
  2117.         if isinstance(cfg.get(key), dict):
  2118.             levels.append(key)
  2119.             flatten_errors(cfg[key], val, levels, results)
  2120.             continue
  2121.         
  2122.         results.append((levels[:], key, val))
  2123.     
  2124.     if levels:
  2125.         levels.pop()
  2126.     
  2127.     return results
  2128.  
  2129.